package com.rem.chat.websocket.netty;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: Themberfue
 * @date: 2025/6/12 19:18
 * @description:
 */
public class HandlerHeartBeat extends ChannelDuplexHandler {
    private static final Logger log = LoggerFactory.getLogger(HandlerHeartBeat.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent ish) {
            if (ish.state().equals(IdleState.READER_IDLE)) {
                Attribute<String> attribute = ctx.channel().attr(AttributeKey.valueOf(ctx.channel().id().toString()));
                String userId = attribute.get();
                log.info("用户id：{} 心跳超时", userId);
                ctx.close();
            } else if (ish.state().equals(IdleState.WRITER_IDLE)) {
                ctx.writeAndFlush("heart");
                log.info("发送心跳包");
            }
        }
    }
}
